package juc;


import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {
    private static int count = 200; //定义count = 0
    private static final ReentrantLock lock = new ReentrantLock();//创建 可重入锁lock 实例


    public static void main(String[] args) {
        final Integer[] thread1 = {0};
        final int[] thread2 = {0};
        for (int i = 1; i <= 2; i++) { //通过for循环创建两个线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //每个线程让count自增100次
                    for (int j = 0; j < 200; j++) {
                        try {
                            lock.lock(); //调用 lock 方法
                            if (count <= 0) return;//防止超卖
                            System.out.println("当前线程名: " + Thread.currentThread().getName());
                            count--;
                            if (Objects.equals(Thread.currentThread().getName(), "线程： 1")) {
                                thread1[0]++;
                            } else {
                                thread2[0]++;
                            }
                        } finally {
                            lock.unlock(); //调用unlock方法释放锁
                        }
                    }
                }
            }, "线程： " + i).start();
        }


        try {
            System.out.println("当前线程名: " + Thread.currentThread().getName());
            Thread.sleep(2000);
            System.out.println("线程1：" + thread1[0]);
            System.out.println("线程2：" + thread2[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }

}
